﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using ShareYou.Entity.Module.Dto;

namespace ShareYou.Configuration
{
    /// <summary>
    /// 插件程序集初始化1.读取程序集  2.读取对应的类型（例如服务注册）
    /// </summary>
    public static class ModuleAssemblyConfig
    {
        /// <summary>
        /// 读取插件程序集
        /// </summary>
        /// <param name="services"></param>
        /// <param name="path">主程序插件目录</param>
        /// <returns></returns>
        public static IList<ModuleAssemblyInfo> LoadModules(this IServiceCollection services, string path)
        {
            if(string.IsNullOrEmpty(path))
                throw new Exception("路径地址不能为空");

            //var moduleFolders = Directory.GetDirectories(path,); //获取插件目录
            var modulerootfolder=new DirectoryInfo(Path.Combine(path));
            var moduleFolders = modulerootfolder.GetDirectories();
            var list = new List<ModuleAssemblyInfo>();
            foreach (var folder in moduleFolders)
            {
                //加载程序集
                var moduleDlls = folder.GetFiles("*.Module.*.dll", SearchOption.AllDirectories);
                if (moduleDlls.Length == 1)
                {
                    var model = new ModuleAssemblyInfo
                    {
                        FolderName = folder.Name,
                        FolderPath = folder.FullName,
                        Assembly = Assembly.LoadFrom(moduleDlls[0].FullName)
                    };
                    list.Add(model);
                }
                else
                {
                    throw new Exception("没一个模块只能存在一个ShareYou.Module.*.dll程序集");
                }
            }
            return list;
        }
    }
}
